package com.cwf.org.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.cwf.basic.annotation.AutoScanPermission;
import com.cwf.basic.util.AjaxResult;
import com.cwf.basic.util.PageInfo;
import com.cwf.basic.util.RegUtils;
import com.cwf.basic.util.RegularRules;
import com.cwf.org.domain.Department;
import com.cwf.org.domain.Employee;
import com.cwf.org.dto.EmployeeRoleDTO;
import com.cwf.org.query.EmployeeQuery;
import com.cwf.org.service.IDepartmentService;
import com.cwf.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/employee")
@Api(value = "员工的API", description = "员工相关的CRUD功能")
@AutoScanPermission(name = "员工管理", desc = "员工管理接口")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @GetMapping
    @ApiOperation(value = "查询所有员工")
    @AutoScanPermission(name = "查询所有员工", desc = "查询所有员工接口")
    public AjaxResult queryAll() {
        try {
            return AjaxResult.success(employeeService.queryAll());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统故障，请联系管理员");
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    @AutoScanPermission(name = "分局ID查询指定员工", desc = "根据ID查询指定员工接口")
    public AjaxResult queryById(@PathVariable("id") Long id) {
        try {
            Employee employee = employeeService.queryById(id);
            return AjaxResult.success(employee);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统故障，请联系管理员");
        }
    }

    @PutMapping
    @ApiOperation(value = "员工信息新增和修改接口")
    @AutoScanPermission(name = "新增或修改员工信息", desc = "新增或修改员工信息接口")
    public AjaxResult insertOrUpdate(@RequestBody Employee employee) {
        try {
            if (Objects.isNull(employee.getId())) {
                employeeService.insert(employee);
            } else {
                employeeService.update(employee);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 获取用户角色信息
     *
     * @param id 用户id
     * @return 返回角色信息
     */
    @GetMapping("/roles/{id}")
    @ApiOperation(value = "根据ID查询员工角色信息接口")
    @AutoScanPermission(name = "根据ID查询员工角色信息", desc = "根据ID查询员工角色信息接口")
    public AjaxResult getRolesById(@PathVariable("id") Long id) {
        try {
            List<Long> roles = employeeService.getRolesById(id);
            return AjaxResult.success(roles);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统故障，请联系管理员");
        }
    }

    /**
     * 分配角色
     *
     * @param employeeRoleDTO 用户和角色信息
     * @return
     */
    @PutMapping("/roles")
    @ApiOperation(value = "存储用户角色信息接口")
    @AutoScanPermission(name = "存储用户角色信息", desc = "存储用户角色信息接口")
    public AjaxResult saveRole(@RequestBody EmployeeRoleDTO employeeRoleDTO) {
        try {
            employeeService.saveRoles(employeeRoleDTO);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除指定员工信息")
    @AutoScanPermission(name = "通过ID删除指定员工信息", desc = "通过ID删除指定员工信息接口")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            employeeService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    @PostMapping
    @ApiOperation(value = "分页查询员工信息")
    @AutoScanPermission(name = "分页查询员工信息", desc = "分页查询员工信息接口")
    public AjaxResult getPage(@RequestBody EmployeeQuery employeeQuery) {
        try {
            PageInfo<Employee> pageInfo = employeeService.queryPage(employeeQuery);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统故障，请联系管理员");
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除员工信息")
    @AutoScanPermission(name = "批量删除员工信息", desc = "批量删除员工信息接口")
    public AjaxResult batchDelete(@RequestBody List<Long> ids) {
        try {
            employeeService.batchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统故障，请联系管理员");
        }
    }

    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile multipartFile, HttpServletResponse response) throws Exception {
        //new一个模板
        ImportParams params = new ImportParams();
        //开始读取，并用list接收，方便处理
        List<Employee> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(), Employee.class, params);
        // 创建一个空数组，用来存放不合法的数据
        ArrayList<Employee> backList = new ArrayList<>();
        for (Employee employee : result) {
            // 不合法的数据加入数组返回前端
            if (!RegUtils.regexpIsTrue(RegularRules.EMAIL, employee.getEmail())){
                backList.add(employee);
            }else{
                // 合法数据关联部门并插入数据库
                Department department = departmentService.queryByName(employee.getDepartment().getName());
                // 部门不存在不设置部门ID
                if (Objects.isNull(department)){
                    department.setId(null);
                }
                employee.setDepartment(department);
                employeeService.insert(employee);
            }
        }
        return AjaxResult.success(backList);
        /*// 不合法的数据导出
        if (!backList.isEmpty()){
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Employee.class, backList);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss-");
            String format = simpleDateFormat.format(new Date());
            String fileName = "不合格数据"+format+".xlsx";
            FileOutputStream outputStream = new FileOutputStream(new File("D:\\Users\\20617\\Desktop\\"+ fileName));
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
            return AjaxResult.error("有数据不合法，请修改数据",backList);
        }
        // 所有数据都合法，插入数据库
        for (Employee employee : result){
            System.out.println(employee);
            Department department = departmentService.queryByName(employee.getDepartment().getName());
            if (Objects.isNull(department)){
                department.setId(null);// 部门不存在不设置部门ID
            }
            employee.setDepartment(department);
            employeeService.insert(employee);
        }
        // 返回不合法的数据
        return AjaxResult.success("导入成功");*/
    }
    @PostMapping("/export")
    public AjaxResult export(@RequestBody EmployeeQuery employeeQuery, HttpServletResponse response) throws IOException {
        List<Employee> list = null;
        String keyword = employeeQuery.getKeyword();
        if ("".equals(keyword.trim())){
            list = employeeService.queryAll();
        }else{
            list = employeeService.queryByKeyWords(keyword);
        }
        //1.配置对象 2.导出类型 3.导出数据集合
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Employee.class, list);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss-");
        String format = simpleDateFormat.format(new Date());
        String fileName = "导出数据"+format+".xlsx";
        // 本地导出
        FileOutputStream outputStream = new FileOutputStream(new File("D:\\Users\\20617\\Desktop\\"+ fileName));

        workbook.write(outputStream);

        outputStream.close();
        workbook.close();
        return AjaxResult.success();
    }
}
